<template>
  <div id="mapBox" class="map-box"></div>
</template>

<script>
import {
  isLocationOutOfChina,
  transformFromWGSToGCJ,
  transformFromGCJToBaidu
} from '@/plugins/geolocation/geolocation.js';

export default {
  props: {
    modelValue: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    return {
      map: null,
      marker: null,
      circle: null, // 圆形覆盖物实例
      userLocation: {
        latitude: 39.9087,
        longitude: 116.3975
      }
    };
  },
  watch: {
    // 监听半径变化
    'modelValue.radius'() {
      if (this.map && this.marker) {
        this.drawCircle();
      }
    }
  },
  mounted() {
    this.initMapWithDefault();
    this.getUserLocation();
  },
  methods: {
    // 获取用户位置
    async getUserLocation() {
      if (!navigator.geolocation) {
        console.log("浏览器不支持地理定位");
        return this.useDefaultLocation();
      }

      try {
        const position = await new Promise((resolve, reject) => {
          navigator.geolocation.getCurrentPosition(resolve, reject, {
            enableHighAccuracy: true,
            timeout: 5000
          });
        });

        const wgs84Coords = {
          longitude: position.coords.longitude,
          latitude: position.coords.latitude
        };

        this.processCoordinates(wgs84Coords);
      } catch (error) {
        console.log("定位失败:", error);
        this.useDefaultLocation();
      }
    },

    // 坐标处理统一方法
    processCoordinates(coords) {
      if (isLocationOutOfChina(coords.latitude, coords.longitude)) {
        console.log("坐标不在中国境内，不进行转换");
        this.updateMapCenter(coords);
      } else {
        const gcj02Coords = transformFromWGSToGCJ(coords.latitude, coords.longitude);
        const baiduCoords = transformFromGCJToBaidu(gcj02Coords.latitude, gcj02Coords.longitude);
        this.updateMapCenter({
          longitude: baiduCoords.longitude,
          latitude: baiduCoords.latitude
        });
      }
    },

    // 使用默认位置
    useDefaultLocation() {
      console.log("使用默认位置");
      this.processCoordinates(this.userLocation);
    },

    // 初始化地图
    initMapWithDefault() {
      this.map = new BMapGL.Map("mapBox");
      this.map.enableScrollWheelZoom(true);
      this.processCoordinates(this.userLocation);
    },

    // 更新地图中心并添加标记
    updateMapCenter(coords) {
      // 清除旧标记
      if (this.marker) {
        this.map.removeOverlay(this.marker);
      }

      const point = new BMapGL.Point(coords.longitude, coords.latitude);
      this.map.centerAndZoom(point, 15);

      // 添加新标记
      this.marker = new BMapGL.Marker(point);
      this.map.addOverlay(this.marker);

      // 信息窗口
      const infoWindow = new BMapGL.InfoWindow(
          `经度：${coords.longitude.toFixed(6)}<br/>纬度：${coords.latitude.toFixed(6)}`,
          {
            offset: new BMapGL.Size(0, -30),
            enableHTML: true
          }
      );
      this.marker.addEventListener("click", () => {
        this.marker.openInfoWindow(infoWindow);
      });

      // 同步数据到父组件
      this.$emit('update:modelValue', {
        ...this.modelValue,
        latitude: coords.latitude,
        longitude: coords.longitude
      });

      // 绘制圆形
      this.drawCircle();
    },

    // 绘制圆形方法
    drawCircle() {
      // 清除旧圆形
      if (this.circle) {
        this.map.removeOverlay(this.circle);
        this.circle = null;
      }

      // 当半径有效时创建新圆形
      if (this.modelValue.radius > 0) {
        const point = new BMapGL.Point(
            this.modelValue.longitude,
            this.modelValue.latitude
        );

        this.circle = new BMapGL.Circle(point, this.modelValue.radius, {
          strokeColor: "#409eff",
          fillColor: "#409eff",
          strokeOpacity: 0.5,
          fillOpacity: 0.2,
          strokeWeight: 2
        });

        this.map.addOverlay(this.circle);

        // 添加点击事件保持地图稳定
        this.circle.addEventListener("click", (e) => {
          if (e && e.domEvent) {
            e.domEvent.stopPropagation();
          }
        });
      }
    }
  }
};
</script>

<style scoped>
.map-box {
  width: 30vw;
  height: 30vh;
  background: #f0f2f5;
  border: 1px dashed #c0c4cc;
  margin: 1vh 0;
}
</style>